package dao

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"listenboos-common/db"
	"listenboos-common/db/gorms"
	"listenboos-common/tools"
	"log"
	"time"
	"ucenter/model"
)

// 点赞
type CollectDao struct {
	db   *mongo.Database
	conn *gorms.GormConn
}

func (c *CollectDao) Update(ctx context.Context, userId int64, trackId int64) (int64, error) {
	var pro model.Collect
	filter := bson.D{bson.E{Key: "userId", Value: userId},
		{Key: "trackId", Value: trackId}}
	col := c.db.Collection(pro.Table())
	err := col.FindOne(ctx, filter).Decode(&pro)
	if err != nil {
		return 0, err
	}
	update := bson.D{{Key: "$set", Value: bson.D{{Key: "isDeleted", Value: 1}}}}

	if pro.IsDeleted == 0 {
		//update := bson.D{bson.E{Key: "$set",
		//	Value: bson.E{Key: "isDeleted", Value: 1}}}
		updateResult, err := col.UpdateOne(context.Background(), filter, update)
		if err != nil {
			log.Fatal(err)
		}
		if updateResult.MatchedCount > 0 && updateResult.ModifiedCount > 0 {
			return 1, nil
		} else {
			logx.Error(errors.New("Document exists but was not modified"))
			return 0, nil
		}
	} else if pro.IsDeleted == 1 {
		update := bson.D{bson.E{Key: "$set",
			Value: bson.E{Key: "isDeleted", Value: 0}}}
		updateResult, err := col.UpdateOne(context.Background(), filter, update)
		if err != nil {
			log.Fatal(err)
		}
		if updateResult.MatchedCount > 0 && updateResult.ModifiedCount > 0 {
			return 0, nil
		} else {
			logx.Error(errors.New("Document exists but was not modified"))
			return 0, nil
		}
	}
	return pro.IsDeleted, nil
}
func (c *CollectDao) Create(ctx context.Context, pro *model.Collect) (int64, error) {
	_, err := c.db.Collection(pro.Table()).InsertOne(ctx, &pro)
	if err != nil {
		return 0, err
	}
	return 1, nil
}
func (c *CollectDao) FindCollectMysql(ctx context.Context, userId int64, trackId int64) (int64, error) {
	session := c.conn.Session(ctx)
	var col model.UserCollect
	err := session.Model(&model.UserCollect{}).Where("user_id=? and track_id = ?", userId, trackId).First(&col).Error
	if err != nil {
		return 0, err
	}
	return col.IsDeleted, nil
}
func (c *CollectDao) FindProcessTo1(ctx context.Context, userId int64, trackId int64) (pro *model.Collect, err error) {
	col := c.db.Collection(pro.Table())
	// 定义查询过滤器
	filter := bson.D{bson.E{Key: "userId", Value: userId},
		{Key: "trackId", Value: trackId}}
	// 定义排序选项，按 createdAt 字段降序排列
	sortOptions := options.FindOne().SetSort(bson.D{{Key: "createTime", Value: -1}})
	err = col.FindOne(context.Background(), filter, sortOptions).Decode(&pro)
	if err != nil {
		return nil, err
	}
	return pro, nil
}
func (c *CollectDao) CreateMysql(ctx context.Context, pro *model.UserCollect) (int64, error) {
	session := c.conn.Session(ctx)
	err := session.Create(&pro).Error
	if err != nil {
		logx.Error(err)
		return 0, errors.New("create user error")
	}
	return 1, nil
}
func (c *CollectDao) UpdateMysql(ctx context.Context, userId int64, trackId int64) (int64, error) {
	session := c.conn.Session(ctx)
	var col model.UserCollect
	now := tools.ToTimeString(time.Now().UnixMilli())
	err := session.Model(&model.UserCollect{}).Where("user_id=? and track_id = ?", userId, trackId).First(&col).Error
	if col.IsDeleted == 0 {
		// 收藏
		col.IsDeleted = 1
		col.UpdateTime = now
		col.CreateTime = now
		err = session.Save(&col).Error
		if err != nil {
			return 1, err
		}
	} else if col.IsDeleted == 1 {
		// 取消收藏
		col.IsDeleted = 0
		col.UpdateTime = tools.ToTimeString(time.Now().UnixMilli())
		session.Save(&col)
	}
	//.Update("is_deleted", 1).Error
	return col.IsDeleted, err
}
func NewCollectDao(db *mongo.Database, mydb *db.ListenDB) *CollectDao {
	return &CollectDao{
		db:   db,
		conn: gorms.New(mydb.Conn),
	}
}
